<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 单独一行 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="角色操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              class="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              class="el-icon-delete"
              size="mini"
              @click="deleteRoleForm(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              class="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加角色表单 -->
      <span>
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer">
        <el-button @click="addialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="40%"
    >
      <el-form
        :model="editRoleForm"
        ref="editRoleFormRef"
        :rules="editRoleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="SetRightDialogVisible"
      width="50%"
      @close="SetRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        ref="treeRef"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      // 所有角色列表数据
      roleList: [],
      //   隐藏添加角色对话框
      addialogVisible: false,
      editRoleDialogVisible: false,
      SetRightDialogVisible: false,
      //  保存所有权限的数据
      rightslist: [],
      //   编辑角色信息
      editRoleForm: {},
      //   添加角色信息
      addForm: {},
      // 树形控件的绑定
      // 当前即将分配角色ID
      roleId: "",
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 默认选中节点的id值
      defKeys: [],
      //   添加角色表单数据
      addForm: {
        roleName: "",
        roleDesc: "",
      },

      // 添加角色规则
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      // 编辑角色规则
      editRoleFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
    };
  },
  // 生命周期函数
  created() {
    this.getRolesList();
  },
  methods: {
    //    获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.roleList = res.data;
      console.log(this.roleList);
    },
    // 重置表单内信息
    addDialogClosed() {
      // 重置表达验证
      this.$refs.addFormRef.resetFields();
    },
    // 添加角色
    addUserInfo() {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid)返回布尔值为true继续走
        if (!valid) return;
        // 发送post请求
        const { data: res } = await this.$http.post("roles", this.addForm);
        // console.log(res)  当status数值为201时则角色创建成功
        if (res.meta.status !== 201) {
          return this.$message.error("用户创建失败！");
        }
        // 创建成功后 1、给出提示信息 2、关闭对话框且刷新保存数据
        this.$message.success("用户创建成功！");
        (this.addialogVisible = false), this.getRolesList();
      });
    },
    // 修改角色信息
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200)
        return this.$message.error("查询角色信息失败！");
      this.editRoleForm = res.data;
      this.editRoleDialogVisible = true;
    },
    //  确定修改角色
    editRoles() {
      this.$refs.editRoleFormRef.validate(async (valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc,
          }
        );
        if (res.meta.status !== 200) {
          this.$message.error("更新角色信息失败！");
        }
        // 隐藏编辑角色对话框
        this.editRoleDialogVisible = false;
        this.$message.success("更新角色信息成功！");
        this.getRolesList();
      });
    },
    // 删除角色
    async deleteRoleForm(id) {
      console.log(id);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("取消了操作!");
      }
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("用户删除失败!");
      }
      this.$message.success("该用户已成功删除!");
      //  刷新并保存数据
      this.getRolesList();
    },
    // 删除标签
    async removeRightById(role, rightId) {
      // 提示用户是否删除
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        this.$message.info("用户取消删除！");
      }
      // console.log('确认了删除')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除角色权限失败！");
      }
      //  防止删除权限后刷新关闭选项卡的问题
      role.children = res.data;
      //  这个则会刷新权限列表，关闭选项卡
      //  this.getRolesList()
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      // 在打开分权对话框之前获取所已选的id
      this.roleId = role.id;

      // 在对话框出现之前获取所有权限的数据
      // 并展现出来一个树形结构
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限的数据失败！");
      }
      // 获取到的权限数据，保存到rightslist[]中
      this.rightslist = res.data;
      console.log(this.rightslist);

      // 递归获取三级节点的ID
      this.getLeafKeys(role, this.defKeys);

      this.SetRightDialogVisible = true;
    },
    // 通过递归的形式获取角色下所有三级权限的ID,并保存到defKeys数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    // 监听分配权限对话框的关闭事件
    SetRightDialogClosed() {
      this.defKeys = [];
    },
    // 分配权限确定按钮
    async allotRights() {
      // 先拿到所有的KEY,获取所有全选或半选的KEY
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if(res.meta.status!==200){
        return this.$message.error('获取权限失败！')

      }
      this.$message.success('权限分配已完成！')
      this.getRolesList()
      this.SetRightDialogVisible = false
      // 所选的权限的 id
      // console.log(keys);
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>